package com.mew.sas.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mew.common.dc.mapper.OnlineGiftMapper;
import com.mew.common.enm.ExitType;
import com.mew.common.entity.events.OnlineGift;
import com.mew.common.util.DateUtils;
import com.mew.sas.config.EventsLastingConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;

@Service
@Slf4j
public class OnlineGiftSasService extends ServiceImpl<OnlineGiftMapper, OnlineGift> {

    @Autowired
    private EventsLastingConfig eventsLastingConfig;

    /**
     * 查询 没有就创建  时间不对也创建
     * @param uid
     * @return
     */
    public OnlineGift getOnlineGift(long uid){

        OnlineGift onlineGift = getById(uid);
        if (null == onlineGift){
            onlineGift = OnlineGift.builder()
                    .userId(uid)
                    .onlineTime(new Date())
                    .receiveType(buildReceiveType())
                    .onlineSecond(0l)
                    .build();
            save(onlineGift);
            return onlineGift;
        }

        //刷新或创建新的
        if (!DateUtils.format(onlineGift.getOnlineTime(),"dd").equals(DateUtils.format(new Date(),"dd"))){
            onlineGift.setOnlineTime(new Date());
            onlineGift.setOnlineSecond(0l);
            onlineGift.setReceiveType(buildReceiveType());
            updateById(onlineGift);
        }
        return onlineGift;
    }

    private String buildReceiveType(){
        int[] onlinetimes = Arrays.stream(eventsLastingConfig.onlinetimes.split(",")).mapToInt(Integer::parseInt).toArray();
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < onlinetimes.length-1; i++) {
            builder.append("0");
        }
        return builder.toString();
    }


    public void enter(long uid){
        OnlineGift onlineGift = getOnlineGift(uid);
        onlineGift.setOnlineTime(new Date());
        updateById(onlineGift);
    }

    public void exit(long uid, ExitType exitType){
        OnlineGift onlineGift = getOnlineGift(uid);
        long currentTime = System.currentTimeMillis();
        long x = (ExitType.Expires == exitType ? currentTime - 1800 * 1000 : currentTime) - onlineGift.getOnlineTime().getTime();
        onlineGift.setOnlineSecond(onlineGift.getOnlineSecond() + (x < 1000 ? 1000 : x));
        log.info("----exit ExitType {} {}", exitType, onlineGift);
        updateById(onlineGift);
    }

}
